Home:ALL Converter>Angular - fetch data from API

Angular - fetch data from API

Ask Time:2018-11-20T06:03:58         Author:sosick

Json Formatter

I have to get data from flickr API. Precisely I need "photo" array from my URL. It works when I getting to data in app.component and operate on any, but I know that this is not a good solution.

I Tried:

photo.ts:

  export class Photo {
    title: string;
    farm: number;
    secret: string;
    server: string;
    owner: string;
    id: string;
  };

app.component.ts:

  export class AppComponent implements OnInit {

    photos: Photo[];

    constructor(private http: HttpService) {}

    ngOnInit() {
      this.getData();
    }

    getData() {
      this.http.getData().subscribe(data => {
        this.photos = data;
      });
    }
  }

and my main problem, http.service.ts:

export class HttpService {

  constructor(private http: HttpClient) { }

  getData(): Observable<Photo[]> {
    return this.http.get('https://api.flickr.com/path')
      .map(res => res.photos.photo);
  }
}

It seems to me that everything should work fine, but I get an error:

ERROR in src/app/http.service.ts(18,23): error TS2339: Property 'photos' does not exist on type 'Object'.

Author:sosick,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53383288/angular-fetch-data-from-api
Joe :

Try implicitly setting res to 'any'\n\ngetData(): Observable<Photo[]> {\n return this.http.get('https://api.flickr.com/path')\n .map((res:any) => res.photos.photo);\n}\n",
2018-11-20T00:05:55
Lucho :

Try this instead in your photo.ts to match the response structure\n\nexport interface Photo {\n title: string,\n farm: number,\n secret: string,\n server: string,\n owner: string,\n id: string,\n isFriend: number,\n isFamily: number,\n isPublic: number\n };\n\n\nAnd in your callback change to this.photos = data.photos.photo",
2018-11-19T22:31:32
yy